<template>
  <custom-modal
    width="1000px"
    :destroyOnClose="true"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    :title="$t('onlineDifferenceChoose')"
    :visible="modalVisibal"
  >
  <!-- 目标版本列表 -->
    <b>
      目标版本
    </b>
    <a-table
      :columns="targetVersionColumns"
      :data-source="dataFormTb"
      :pagination="false"
      rowKey="id"
      :scroll="{y:190}"
      style="min-height:190px"
    >
      <template slot="createTime" slot-scope="text">
        <table-ellipsis
          :tableEllipsisIsTurnLine="false"
          :text="text ? $options.filters.moment(text) : '_'"
        ></table-ellipsis>
      </template>
      <template slot="serialNo" slot-scope="text">
         <span v-if="text">{{text}}</span>
          <span v-if="!text">-</span>
      </template>
      <template #operation="text">
        <span class="set-margin">
          <a-icon type="edit" />
          <a @click="clickRowOperation('edit',text)">{{ $t('edit') }}</a>
        </span>
        <span>
          <i class="iconfont icon-shanchu deleteUlr"></i>
          <a @click="clickRowOperation('delete',text)">{{ $t('delete') }}</a>
        </span>
      </template>
      </a-table>
  <a-form-model
      class="model-content"
      ref="createModal"
      :model="modal"
      :rules="uploadRules"
    >
    <a-row :gutter="[36,10]">
      <a-col :md="8" :sm="24">
        <a-form-model-item :label="$t('dllFileClassName')" >
           <a-input v-model="modal.fileReprogramType" disabled/>
        </a-form-model-item>
       </a-col>
       <!-- 预计安装时间 -->
      <a-col :md="8" :sm="24">
        <a-form-model-item :label="$t('estimatedInstallTime')+'(s)' " prop="installSec">
          <a-input-number
          style="width: 100%"
            v-model="modal.installSec"
            :placeholder="$t('pleaseInput')+$t('estimatedInstallTime')"
          ></a-input-number>
        </a-form-model-item>
      </a-col>
      <!-- 超时时长 -->
      <a-col :md="8" :sm="24">
        <a-form-model-item :label="$t('timeout')+'(s)' " prop="timeoutSec">
          <a-input-number
            style="width: 100%"
            v-model="modal.timeoutSec"
            :placeholder="$t('pleaseInput')+$t('timeout')"
          ></a-input-number>
        </a-form-model-item>
      </a-col>
    </a-row>
  </a-form-model>
        <!-- 原始版本列表 -->
      <b>
        原始版本
      </b>
      <a-table
        :columns="targetVersionColumns"
        :data-source="dataSelected"
        :pagination="false"
        rowKey="id"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange,onSelect: onSelect }"
        :scroll="{y:260}"
        style="min-height:260px"
      >
        <template slot="createTime" slot-scope="text">
          <table-ellipsis
            :tableEllipsisIsTurnLine="false"
            :text="text ? $options.filters.moment(text) : '_'"
          ></table-ellipsis>
        </template>
        <template slot="serialNo" slot-scope="text">
          <span v-if="text">{{text}}</span>
          <span v-if="!text">-</span>
        </template>
        <template #operation="text, record">
          <a @click="deleteSelected(record)" style="color: red;" type="danger" :ghost="true" size="small">{{ $t('delete') }}</a>
        </template>
      </a-table> 
       <a-pagination
        :pageSizeOptions="['10', '20', '50']"
        :current="pageInfo.pageNo"
        :pageSize="pageInfo.pageSize"
        :total="pageInfo.totalCount"
        :totalPage="pageInfo.totalPage"
        :showSizeChanger="true"
        :showQuickJumper="true"
        :showTotal= "(total)=> '共'+total+'条'"
        @change="changePage"
        @showSizeChange="showSizeChange"
        style="display: flex;float:right;"
        /> 
  </custom-modal>
</template>
<script>
import CustomModal from '@/components/CustomModal/index.vue'
import {targetVersionColumns}from '../config/list'
import { checkIsRangeInteger } from '@/utils/validate'
export default {
   props: {
    selectedVersion: {
      type: Array,
      default: ''
    }
  },
  name: 'OnlineDifference',
  components: {
    CustomModal,
  },
  data () {
    return {
      pageInfo: {
        pageSize: 10,
        pageNo: 1,
        totalCount: 0,
        totalPage: 0
      },
      currentId:'',
      isDiffDone:false,
      dataFormTb:[],
      dataSelected:[],
      preSelectedRowKeys:[],
      preOriginalVersionList:[],
      selectedRowKeys:[],
      selectedRows:[],
      targetVersionColumns,
      modalVisibal: false,
      modal:{
        originalVersionList:[]
      },
      dllNameDictCode:[],
      uploadRules: {
        installSec: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkIsRangeInteger(1, 2147483647) } ],
        timeoutSec: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkIsRangeInteger(1, 2147483647) }],
        fileReprogramType: [{ required: true, message: this.$t('pleaseSelect') }],
      },
    }
  },
  watch: {
    selectedVersion: {
      handler(val){
        this.selectedRowKeys=val
      }
    }
  },
  methods: {
     // 分页
    changePage (page) {
      // this.selectedRowKeys=[],
      // this.selectedRows=[],
      this.pageInfo.pageNo = page
      this.loadData()
    },
    showSizeChange (current, size) {
      this.pageInfo.pageSize = size
      this.pageInfo.pageNo = 1
      this.loadData()
    },
    loadData(data) {
      let params = {
        pageSize: this.pageInfo.pageSize,
        pageNo: this.pageInfo.pageNo,
        id:data?data:this.currentId
      }
      this.$api.getOnlineDiffOrigin(params).then((res)=>{
        this.dataSelected=res.data
        this.pageInfo.totalCount = res.totalCount
        this.pageInfo.totalPage = res.totalPage
      }).finally(() => {

      })
    },
    // 比较版本号大小方法
    compareVersions(version1, version2) {
      var arr1 = version1.split('.');
      var arr2 = version2.split('.');
      // 遍历数字数组进行逐段比较
      for (var i = 0; i < Math.max(arr1.length, arr2.length); i++) {
        var num1 = parseInt(arr1[i] || 0); // 如果数组长度不够，则将缺失部分补0
        var num2 = parseInt(arr2[i] || 0);
        if (num1 < num2) {
          return -1; // 版本1小于版本2
        } else if (num1 > num2) {
          return 1; // 版本1大于版本2
        }
      }
      return 0; // 版本1等于版本2
    },
    onSelectChange(selectedRowKeys, selectedRows){
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows=selectedRows
      // this.modal.originalVersionList = this.selectedRows
    },
    onSelect(record, selected){
      if(selected){
        let compareResult= this.compareVersions(record.versionNumber,this.modal.targetVersionList[0].versionNumber,)
        if(compareResult>0){
          this.$message.warning(this.$t('jrbbbmbbbg'))
        }
      }
    },
    // 显示隐藏
    show (val,id) {
      this.currentId=id
      this.$api.getOnlineDiffList(id).then((res)=>{
        this.dataFormTb=res.data.targetVersionList
        this.modal.targetVersionList=res.data.targetVersionList
        this.modal.fileReprogramType=res.data.fileReprogramType
        this.modal.fileReprogramTypeName=res.data.fileReprogramTypeName
      })
      // this.$api.getOnlineDiffOrigin({id:id,pageSize: this.pageInfo.pageSize, pageNo: this.pageInfo.pageNo}).then((res)=>{
      //   this.dataSelected=res.data
      // })
      this.loadData(id)
      this.preSelectedRowKeys=[...this.selectedRowKeys]
      this.preOriginalVersionList=[...this.modal.originalVersionList]
      if(this.selectedRowKeys.length==0){
        this.$set(this.modal,'installSec',undefined)
        this.$set(this.modal,'timeoutSec',undefined)
      }
      this.modalVisibal = val
    },
    // 对话框点击保存
    handleOk () {
      this.$api.getOnlineDiffOrigin({
        pageSize: 999,
        pageNo: 1,
        id:this.currentId
      }).then((res)=>{
        const allData = res.data
        const selectedArr=[]
        allData.forEach((item)=>{
          this.selectedRowKeys.forEach((id)=>{
            if(id==item.id){
              selectedArr.push(item)
            }
          })
        })
        this.modal.originalVersionList=[...selectedArr]
        this.$refs.createModal.validate(valid => {
          if (valid) {
            if(this.modal.originalVersionList.length==0){
              this.$message.warning(this.$t('pleaseSelect')+'原始版本')
              return
            }
            this.$api.createOnlineDiffFile(this.modal)
              .then(res=> {
                this.modalVisibal = false
                this.isDiffDone=true
                // this.resetData()
                this.$emit('addOrEditDone', res.data,this.selectedRowKeys)
              })
          }
        })
      })
    },
    // 对话框点击取消
    handleCancel () {
      this.resetData()
      this.modalVisibal = false
    },
    // 手动重置数据
    resetData () {
      this.selectedRowKeys=[...this.preSelectedRowKeys]
      this.$set(this.modal,'originalVersionList',[...this.preOriginalVersionList])
      if(!this.isDiffDone){
        this.selectedRowKeys = []
        this.selectedRows = []
        this.modal.originalVersionList = []
        this.$set(this.modal,'installSec',undefined)
        this.$set(this.modal,'timeoutSec',undefined)
      }
    }
  }
}
</script>
<style lang="less" scoped>
</style>
